package com.hn.kiss.config.conf;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hn.kiss.modules.sys.security.AdminUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 填充器
 *
 * @author nieqiurong 2018-08-10 22:59:23.
 */
@Slf4j
@Component
public class MpMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "createUser", String.class, getUserId());
        this.strictInsertFill(metaObject, "id", String.class, IdUtil.simpleUUID());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "modifyDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "modifyUser", String.class, getUserId());
    }

    /**
     * 获取登录用户id
     * @return
     */
    private String getUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AdminUserDetails userDetails = null;
        try {
            userDetails = (AdminUserDetails)authentication.getPrincipal();
            return userDetails.getUser().getId();
        }catch (Exception e){
            log.error(e.toString());
            log.error(authentication.getPrincipal().toString());
        }
        return null;
    }
}
